<template>
  <div>
    <el-form
      label-width="120px"
      :model="dataForm"
      :rules="rules"
      ref="dataForm"
      @keyup.enter.native="getDataList(true)"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="出险人姓名:" prop="insuredName">
            <el-input v-model="dataForm.insuredName" placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="证件类型:" prop="certificateType">
            <el-select v-model="dataForm.certificateType">
              <el-option
                v-for="item in Consts.certificateTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="证件号码:" prop="certificateNo">
            <el-input
              v-model="dataForm.certificateNo"
              placeholder=""
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="集团名称:" prop="corpName">
            <el-input v-model="dataForm.corpName" placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="保单号:" prop="policyNo">
            <el-input v-model="dataForm.policyNo" placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="案件状态:" prop="caseStatus">
            <el-select v-model="dataForm.caseStatus">
              <el-option
                  v-for="item in Consts.caseStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="案件编号:" prop="caseNo">
            <el-input v-model="dataForm.caseNo" placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="报案时间:" size="small" prop="reportTime">
            <el-date-picker
              v-model="dataForm.reportTime"
              type="daterange"
              value-format="yyyy-MM-dd"
              :picker-options="reportTimeOption"
			  :clearable="clearable"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="max-width: 238px"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button @click="resetForm('dataForm')">重置条件</el-button>
            <el-button
              v-if="isAuth('claim:claimcase:pageList')"
              type="primary"
              @click="getDataList(true)"
              >查询</el-button
            >
            <!-- <el-button type="primary" @click="goCaseDetail()">记录详情</el-button> -->
          </el-form-item>
        </el-col>
      </el-row>
    
    <el-row :gutter="24">
		<el-col :span="20">
			<el-button
			  v-if="isAuth('claim:claimcase:save')"
			  type="primary"
			  plain
			  icon="el-icon-plus"
			  @click="addCase()"
			  >新增报案</el-button
			>
		</el-col>
		<el-col :span="4" style="display: flex;">
			<el-button
			  type="text"
			  icon="el-icon-download"
			  plain
			  @click="exportCase()"
			  >导出理赔报表</el-button>
			<el-upload ref="upload" action="#" style="margin-left: 10px;"
			             v-loading.fullscreen.lock="fullscreenLoading"
						 element-loading-text="拼命导入中"
						 element-loading-spinner="el-icon-loading"
						 element-loading-background="rgba(0, 0, 0, 0.8)"
						 :show-file-list="true"
						 :before-upload="handleBeforeUpload"  
						 :on-error="handleUploadError"
						 :on-success="handleUploadSuccess"
						 :limit="1"
						 :on-exceed="handleExceed" 
						 :http-request="submitFileUpload"
						 accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
						 :file-list="fileList">
			  <el-button size="medium" type="text" icon="el-icon-upload2" plain>导入理赔报表</el-button>
		   </el-upload>
		</el-col>
    </el-row>
	</el-form>
    <el-table
      class="tableClass"
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="50"> </el-table-column>
      <el-table-column
        prop="caseNo"
        header-align="center"
        align="center"
        label="案件编号"
      >
      </el-table-column>
      <el-table-column
        prop="policyNo"
        header-align="center"
        align="center"
        label="保单号"
      >
      </el-table-column>
      <el-table-column
        prop="corpName"
        header-align="center"
        align="center"
        label="集团名称"
      >
      </el-table-column>
      <el-table-column
        prop="insuredName"
        header-align="center"
        align="center"
        label="出险人姓名"
      >
      </el-table-column>
      <el-table-column
        prop="certificateNo"
        header-align="center"
        align="center"
        label="证件号码"
      >
      </el-table-column>
      <el-table-column
        prop="reportTime"
        header-align="center"
        align="center"
        label="报案时间"
      >
      </el-table-column>
      <!-- <el-table-column
          prop="accidentDescription"
          header-align="center"
          align="center"
          label="案情描述"
      >
      </el-table-column> -->
      <el-table-column prop="caseStatus" header-align="center" align="center" width="180" label="案件状态">
        <template slot-scope="scope">
          <div v-for="item in Consts.caseStatusList" :key="item.value">
            <el-tag v-if="item.value == scope.row.caseStatus" >
              {{ item.label }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <!--      <el-table-column prop="firstStatus" header-align="center" align="center" width="180" label="首次状态">
        <template slot-scope="scope">
          <div v-for="item in Consts.firstStatusList" :key="item.value">
            <el-tag v-if="item.value == scope.row.firstStatus" >
              {{ item.label }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="secondStatus" header-align="center" align="center" width="180" label="二次理赔">
        <template slot-scope="scope">
          <div v-for="item in Consts.firstStatusList" :key="item.value">
            <el-tag v-if="item.value == scope.row.secondStatus" >
              {{ item.label }}
            </el-tag>
          </div>
        </template>
      </el-table-column>-->
      <el-table-column
        prop="firstAcceptorName"
        header-align="center"
        align="center"
        label="理赔专员"
      >
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="200"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleViewRecord(scope.row)"
            >查看
          </el-button>
		  <el-button v-if="isAuth('claim:claimcase:delete')" 
		    type="danger"
		    size="mini"
		    @click="deleteHandle(scope.row)"
		    >删除
		  </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-show="showPagination"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <!-- 弹窗, 新增 / 修改 -->
    <AddCase
      v-if="addVisible"
      ref="addCase"
      @refreshDataList="getDataList"
    ></AddCase>
    <ClaimRecords v-if="claimRecordsVisible" ref="claimRecords"></ClaimRecords>
  </div>
</template>

<script>
import Vue from 'vue'
import AddCase from "./case-add.vue";
import ClaimRecords from "./claim-records.vue";
export default {
  data() {
    return {
	  showPagination:false,
	  clearable:false,
	  fullscreenLoading: false,
	  fileList:[],
      dataForm: {
        insuredName: "",
        certificateType: "",
        certificateNo: "",
        corpName: "",
        policyNo: "",
        firstStatus: "",
        caseNo: "",
        reportTimeStart: null,
        reportTimeEnd: null,
      },
      reportTimeOption: {
        onPick: ({ maxDate, minDate }) => {
          this.dataForm.reportTimeStart = this.pickerDateFormat(
            new Date(minDate)
          );
          this.dataForm.reportTimeEnd = this.pickerDateFormat(
            new Date(maxDate)
          );
        },
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入活动名称",
            trigger: "blur",
          },
          {
            min: 3,
            max: 5,
            message: "长度在 3 到 5 个字符",
            trigger: "blur",
          },
        ],
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addVisible: false,
      claimRecordsVisible: false,
	  taskInterval: null,
    };
  },
  components: {
    AddCase,
    ClaimRecords,
  },
  activated() {
    this.getDataList();
  },
  methods: {
    // 获取数据列表
    getDataList(showPagination) {
	  if(showPagination){
		  this.showPagination = true;
	  }else{
		  this.showPagination = false;
	  }
      this.dataListLoading = true;
      console.log("paramData==>", this.dataForm);
      this.$http({
        url: this.$http.adornUrl("/claim/claimcase/pageList"),
        method: "POST",
        data: this.$http.adornData({
          page: this.pageIndex,
          pageSize: this.pageSize,
          params: this.dataForm,
        }),
      }).then(({ data }) => {
        this.dataListLoading = false;
        if (data && data.code === 0) {
          this.dataList = data.data.records;
          this.totalPage = data.data.total;
        } else {
          if (data && data.msg) {
            this.$message.warning(data.msg);
          }
          this.dataList = [];
          this.totalPage = 0;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
	  this.dataForm.reportTimeStart=null
	  this.dataForm.reportTimeEnd=null
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList(true);
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList(true);
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addCase(id) {
      this.addVisible = true;
      this.$nextTick(() => {
        this.$refs.addCase.init(id);
      });
    },
    pickerDateFormat: function (date) {
      // eslint-disable-next-line one-var
      let d = new Date(date),
        month = "" + (d.getMonth() + 1),
        day = "" + d.getDate(),
        year = d.getFullYear();

      if (month.length < 2) month = "0" + month;
      if (day.length < 2) day = "0" + day;

      return [year, month, day].join("-");
    },
    goCaseDetail: function () {
      this.$router.push({ name: "case-detail-tab", query: { id: "1" } });
    },
    handleViewRecord: function (row) {
      let params = {
        id: row.id,
        caseNo: row.caseNo,
        corpName: row.corpName,
        insuredName: row.insuredName,
        certificateNo: row.certificateNo,
        policyNo: row.policyNo,
        reportTime: row.reportTime,
      };
      this.claimRecordsVisible = true;
      this.$nextTick(() => {
        this.$refs.claimRecords.init(JSON.stringify(params));
      });
    },
    deleteHandle: function (row) {
      this.$confirm(`确定对[案件编号=${row.caseNo}]进行[删除]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/claim/claimcase/delete/'+row.id),
          method: 'delete',
          data: {}
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => {})
    },
      exportCase: function () {
		  var params = this.$http.adornData({
			token :Vue.cookie.get('token'),
            page: this.pageIndex,
            pageSize: this.pageSize,
            ...this.dataForm,
          },"true","form");
		  let url = this.$http.adornUrl("/claim/claimcase/export")
		  window.location.href = `${url}?${params}`
	},
	downloadFile(url) {
	  const xhr = new XMLHttpRequest();
	  xhr.open('GET', url);
	  xhr.responseType = 'blob';
	  xhr.onload = () => {
	    const blob = xhr.response;
	    const url = window.URL.createObjectURL(blob);
	    const a = document.createElement('a');
	    a.href = url;
	    a.download = '理赔报表'+this.getCurrentDateTimeString()+'.xls';
	    document.body.appendChild(a);
	    a.click();
	    a.remove();
	    window.URL.revokeObjectURL(url);
	  };
	  xhr.onerror = (e) => {
	    console.error(e);
	  };
	  xhr.send();
	},
	getCurrentDateTimeString() {
	  const now = new Date();
	  const year = now.getFullYear();
	  const month = String(now.getMonth() + 1).padStart(2, '0');
	  const day = String(now.getDate()).padStart(2, '0');
	  const hours = String(now.getHours()).padStart(2, '0');
	  const minutes = String(now.getMinutes()).padStart(2, '0');
	  const seconds = String(now.getSeconds()).padStart(2, '0');
	  return `${year}${month}${day}${hours}${minutes}${seconds}`;
	},
	handleBeforeUpload(file) {
	  console.log(file.type)
	  let fileName = file.name
		let fileType = fileName.substring(fileName.lastIndexOf('.') + 1);

		// 判断上传文件格式
		if (file) {
			if ((fileType != 'xlsx') && (fileType != 'xls')) {
				this.$message({
					type: 'warning',
					message: '格式错误，请重新上传！'
				})
				return;
			}
		} else {
			this.$message({
				type: 'warning',
				message: '请上传附件！'
			})
			return;
		}
	},
	handleUploadSuccess: function(response, file, fileList){
		console.log("response", response)
		this.$refs.upload.clearFiles();
	},
	handleUploadError: function(err, file, fileList){
		console.log("err", err)
		this.$refs.upload.clearFiles();
	},
	handleExceed: function(err, file, fileList){
		console.log("err", err)
		this.$refs.upload.clearFiles();
	},
    submitFileUpload: function (req) {
      console.log(req);
	  this.fullscreenLoading = true
      let that = this;
      let reader = new FileReader();
      reader.readAsDataURL(req.file);
      reader.onload = function () {
		let formData = new FormData();
		formData.append("file", req.file);
        that
          .$http({
            url: that.$http.adornUrl("/claim/claimcase/importExcel"),
            method: "post",
            data: formData,
			headers: {'Content-Type': 'multipart/form-data' },
			timeout: 1000*60*5
          })
          .then(({ data }) => {
            if (data && data.code === 0 && data.data) {
				//
				let taskCode = data.data
				that.taskInterval = setInterval(function(){
					that.queryTaskStatus(taskCode)
				},1000)
            } else if (data && data.msg) {
			  that.fullscreenLoading = false
              that.$alert(data.msg, '导入结果', {
				confirmButtonText: '确定',
				callback: action => {
				  
				}
              });
            }else{
			    that.fullscreenLoading = false
				that.$alert("导入异常", '导入结果', {
					confirmButtonText: '确定',
					callback: action => {
					  
					}
				});
			}
          });
		  that.$refs.upload.clearFiles();
      };
    },
	queryTaskStatus: function(taskCode){
		let that = this;
		this.$http({
		      url: that.$http.adornUrl("/claim/claimcase/queryTaskStatus?taskCode="+ taskCode),
		      method: "get",
		    })
		    .then(({ data }) => {
		      if (data && data.code != 0) {
				  clearInterval(that.taskInterval)
				  that.fullscreenLoading = false
				  that.$refs.upload.clearFiles();
				  that.$alert(data.msg, '导入结果', {
					confirmButtonText: '确定',
					callback: action => {
					}
				  });
				  return
		      }
			  let task = data.data
			  if(task.status == 1 || task.status == 2){
				  clearInterval(that.taskInterval)
				  that.fullscreenLoading = false
				  that.$refs.upload.clearFiles();
				  that.$alert(task.msg, '导入结果', {
					confirmButtonText: '确定',
					callback: action => {
					}
				  });
				  that.getDataList();
			  }
		});		
	},
  },
};
</script>

<style>
.tableClass {
  margin-top: 15px;
}
</style>
